package com.gas.gm.util.converter.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import com.gas.gm.model.Account;
import com.gas.gm.service.AccountService;
import com.gas.gm.util.GasContextHelper;

@SuppressWarnings("deprecation")
public class AccountXMLCreator extends GasXMLCreator<Account> {
	
	List<Account> accounts;
	
	Document doc;
	
	public AccountXMLCreator() {
		accounts=new ArrayList<Account>();
		loadData();
		createDocument();
	}

	@Override
	public void loadData() {
		AccountService accountService=GasContextHelper.getApplicationContext().getBean(AccountService.class);
		accounts=accountService.findAllAccounts();
	}

	@Override
	public void createDocument() {
		DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder db=dbf.newDocumentBuilder();
			doc=db.newDocument();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void createDOMTree() {
		Element root=doc.createElement("gas-accounts");
		doc.appendChild(root);
		
		Iterator<Account> iter=accounts.iterator();
		while(iter.hasNext()){
			Account acc=iter.next();
			Element el=createElements(acc);
			root.appendChild(el);
		}
	}

	@Override
	public void printToFile(String filename) throws IOException {
		OutputFormat format=new OutputFormat(doc);
		format.setIndenting(true);
		XMLSerializer serializer=new XMLSerializer(new FileOutputStream
				(new File(filename)),format);
		serializer.serialize(doc);
	}

	@Override
	protected Element createElements(Account a) {
		Element accountEl=doc.createElement("account");
		
		Element systemIdEl=doc.createElement("systemId");
		Text idText=doc.createTextNode(a.getSystemId());
		systemIdEl.appendChild(idText);
		accountEl.appendChild(systemIdEl);
		
		Element passEl=doc.createElement("password");
		Text passText=doc.createTextNode(a.getPassword());
		passEl.appendChild(passText);
		accountEl.appendChild(passEl);
		
		Element comNumberEl=doc.createElement("companyNumber");
		Text comNTex=doc.createTextNode(a.getCompanyNumber());
		comNumberEl.appendChild(comNTex);
		accountEl.appendChild(comNumberEl);
		
		Element tokenEl=doc.createElement("token");
		Text tokenText=doc.createTextNode(String.valueOf(a.getToken().getToken()));
		tokenEl.appendChild(tokenText);
		accountEl.appendChild(tokenEl);
		
		return accountEl;
		
	}

}
